package servlets;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class WriteReadFile 
{	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public WriteReadFile() 
	{}
	
	public static void write(String log, String fileLocation, String fileName)
	{
		String txt = "";
		File repositoryPath = new File(fileLocation);
		if(!repositoryPath.exists())
		{
			if(repositoryPath.mkdirs())
				System.out.println("Log directory built");
		}
		try
		{
			txt = log + "\n" + read(fileLocation + fileName);
			FileWriter fw = new FileWriter(fileLocation + fileName);
			BufferedWriter output = new BufferedWriter(fw);
			output.write(txt);
			output.flush();
			output.close();
		 }
		 catch(IOException ioe)
		 {
			 System.out.println("erreur write(): " + ioe );
			 Notification.getNotification(Notification.file_read,fileLocation + fileName);
		}	
	}
	
	public static void writeDiary(String msg, String  location,String diary)
	{
		File repositoryPath = new File(location);
		if(!repositoryPath.exists())
		{
			if(repositoryPath.mkdirs())
				System.out.println("Diary directory built");
		}
		try
		{
			FileWriter fw = new FileWriter(location + diary);
			BufferedWriter output = new BufferedWriter(fw);
			output.write(msg);
			output.flush();
			output.close();
		 }
		 catch(IOException ioe)
		 {
			 System.out.println("erreur write(): " + ioe );
			 Notification.getNotification(Notification.file_read,diary);
		}	
	}
	
	public static String read(String filetoread)
	{
		String txt = "";
		File file = new File(filetoread);
		if(file.exists())
		{
			String line = "";
			try
			{
				FileReader fr = new FileReader(file);
				BufferedReader br = new BufferedReader(fr);
				while((line = br.readLine()) != null) 
				{
				 txt = txt + line + "\n";
				}
				 br.close();
			 }
			 catch(IOException ioe)
			 {
				 System.out.println("erreur read() : " + ioe);
				 Notification.getNotification(Notification.file_read,filetoread);
			 }
		}
		 return txt;
	}

}

